(function(){
    if (window.performance || window.webkitPerformance) {
        var perf = window.performance || window.webkitPerformance;
        var timing = perf.timing;
        var navi = perf.navigation;
        var timer = setInterval(function() {
            if (0 !== timing.loadEventEnd) {


                clearInterval(timer);
                var data = {
                    url: window.location.href,
                    ua: window.navigator.userAgent,
                    dns :timing.domainLookupEnd - timing.domainLookupStart,
                    tcp :timing.connectEnd - timing.connectStart,
                    request : timing.responseEnd -timing.responseStart,
                    blank : timing.domLoading - timing.fetchStart,
                    domready : timing.domContentLoadedEventEnd - timing.fetchStart,
                    onload : timing.loadEventEnd - timing.fetchStart,
                    isdirty : 0
                };
                if(data.dns <0 || data.dns >500000){
                    data.isdirty = 1;
                }else if(data.tcp <0 || data.tcp >500000){
                    data.isdirty = 1;
                }else if(data.request <0 || data.request >500000){
                    data.isdirty = 1;
                }else if(data.blank <0 || data.blank >500000){
                    data.isdirty = 1;
                }else if(data.domready <0 || data.domready >500000){
                    data.isdirty = 1;
                }else if(data.onload <0 || data.onload >500000){
                    data.isdirty = 1;
                }
                if(typeof window.performance.getEntries == 'function'){
                    var imageAveTime = getImageAverageLoadTime();
                }else{
                    var imageAveTime = 0;
                }
                var imageErrorNumber = getImageErrorNumber();
                data.imageErrorNumber = imageErrorNumber;
                data.imageAveTime = imageAveTime;
                data.imageTotal = document.querySelectorAll('.VAct_modelBox img').length;

                try{
                    var connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
                    data.networkType = connection.type ? connection.type : connection.effectiveType;
                }catch(e){

                }

                sendFrontMonitor(data);
                if(window.__reportParams && window.__reportParams.pv != 'no'){
                    ActionDataReport.sendLoadTime(data.onload / 1000);
                }

                //加载各种上报js
                window.FY.loadScript('http://i.gtimg.cn/channel/components/moggy/maya/maya-1.2.js?rpt_bid=502&monitor_try=31');//maya上报
                window.FY.loadScript('http://imgcache.qq.com/club/client/imgReport/imgReport.js',function(){
                    imgReport.init({
                        id : 10004,
                        subid : 401,
                        pageLoadTime :window.__timePoints.startTime
                    });
                });//图片上报
                //百度统计
                var _hmt = _hmt || [];
                (function() {
                    var hm = document.createElement("script");
                    hm.src = "https://hm.baidu.com/hm.js?45f3607f758a4fad66b510fb7dd80e70";
                    var s = document.getElementsByTagName("script")[0];
                    s.parentNode.insertBefore(hm, s);
                })();


            }
        }, 100);
    }
    function inDomain(src){
        return src.indexOf('.qpic.cn') >= 0 || src.indexOf('.gtimg.com') >= 0;
    }
    function getImageErrorNumber(){
        var num = 0;
        var pageImgs = document.querySelectorAll('.VAct_modelBox img');

        for(var i = 0; i < pageImgs.length; i++){
            var img = pageImgs[i], src = img.getAttribute('src');
            if(src.indexOf('.qpic.cn') >= 0 || src.indexOf('.gtimg.com') >= 0){
                if(img.complete && img.naturalWidth == 0){ // 加载失败
                    FY.reportJsError('image加载失败',src,0,4,3);
                    
                    num ++;
                }
            }
        }
        return num;
    }
    function getImageAverageLoadTime(){
        var sumTime = 0;
        var num = 0;
        try{
            var resources = window.performance.getEntries() || [];
            for (var i = 0; i < resources.length; i++) {
                var resource = resources[i];

                if (resource.initiatorType == 'img') {
                    var src = resource.name.replace('http:', '').replace('https:', '').replace('//', ''),
                        msg = '', type = 0,
                        loadTime = Math.max(Math.round(resource.responseEnd - resource.fetchStart), 0);

                    if (src.indexOf('.qpic.cn') >= 0 || src.indexOf('.gtimg.com') >= 0) {
                        sumTime = sumTime+loadTime;
                        num++
                    }
                }
            }
        }catch(e){

        }

        return parseInt(sumTime/num);
    }
    function sendFrontMonitor(data){
        if(window.__reportParams && window.__reportParams.pv == 'no'){
            return false;
        }
        var url = window.FY_HOST.manageUrl + '/common/report/frontmonitor', param = [];

        for(var k in data){
            param.push(k + '=' + encodeURIComponent(data[k]));
        }
        for(var k in window.FY_HOST){
            if(k == 'citoken'  || k == 'timestamp'){
                param.push(k + '=' + encodeURIComponent(window.FY_HOST[k]));
            }
        }
        var img = new Image();
        img.onload = img.onerror = function () {
            img = null;
        };
        img.src = url + '?' + param.join('&') + '&r=' + (new Date()).getTime() + '&isAdvanced=1';
    }

    /**
     * 转化行为上报
     */
    var ActionDataReport = {
        send: function(url, data){
            data = data || {};
            data = $.extend(data, window.__reportParams);

            var paramArray = ['r=' + Date.now()];
            for(var key in data){
                if(data.hasOwnProperty(key)){
                    paramArray.push(key + '=' + encodeURIComponent(data[key] || ''));
                }
            }

            var img = new Image();
            img.onload = img.onerror = function(){
                img = null;
            };
            img.src = url + '?' + paramArray.join('&') + '&isAdvanced=1';
        },
        sendAction: function(type){
            var clickId = {
                'slide': 1,//滑动屏幕
                'form': 2,//提交表单
                'phone': 3,//拨打电话
                'msg': 4,//发送短信
                'download': 5,//下载按钮
                'map': 6,//地图导航
                'connectqq': 7,//qq咨询
                'online_comm': 8,//在线咨询
                'wxcard':9,//微信卡券
                'tel' : 10, //门店的拨打电话
                'location' : 11, //门店的坐标导航
                'other': 0
            }[type || 'other'];

            this.send(FY_HOST.customUrl + '/stat/click', {click_id: clickId});
        },
        stayTime: function(){
            // 前10s每2s一次，后面10s一次，超过120s停止上报
            function sendStayTime(){
                var viewTime = ((+new Date) - window.__timePoints.startTime);
                ActionDataReport.send(FY_HOST.customUrl + '/stat/pagestay', {view_time: viewTime / 1000});
            }

            var interval = 2000, totalTime = 0;
            var timer = window.setInterval(function(){
                sendStayTime();
                totalTime += interval;

                if(totalTime == 10 * 1000){
                    interval = 10000;

                    window.clearInterval(timer);
                    timer = window.setInterval(function(){
                        sendStayTime();
                        totalTime += interval;

                        if(totalTime == 120 * 1000){
                            window.clearInterval(timer);
                        }
                    }, interval);
                }
            }, interval);
        },
        sendPv: function(){
            this.send(FY_HOST.customUrl + '/stat/pv', {});
        },
        sendLoadTime: function(loadTime){
            this.send(FY_HOST.customUrl + '/stat/loadtime', {load_time: loadTime});
        }
    };

    /**
     * 像素api的上报
     * @param {type} 上报的类型 tel sms button form location等
     * @param {advertiserId} advertiserId
     * @param {conversionId} conversionId
     * @param {form} form表单，jquery对象
     */
    var pixelReport = function(type,formid){
        var gdt_tracker = window.gdt_tracker || [];
        var r = window.__reportParams
/*        debugger
        if(type === 'pv') {


            gdt_tracker.push(["set_account_id", r.u_id]);
            gdt_tracker.push(["add_action", "TRACK_CONVERSION", r['conversion_id_map'].pv]);
            gdt_tracker.push(["send"]);


            return ;
        }*/
        if (!r['conversion_id_map'] || !r['conversion_id_map'][type]) return ;

        gdt_tracker.push(["set_account_id", r['pixel_u_id'] ]);
        if(type == 'phone'){
            gdt_tracker.push(["add_action", "TRACK_CONVERSION" , r['conversion_id_map'].phone]);
        }else if(type == 'form'){
            var fromInfo = {};
            var form = $('#' + formid + ' form');
            form.find('.pixel-report').each(function(e){
                var key = $(this).data('key');
                var value = $(this).find('input').val() ? $(this).find('input').val() : $(this).find('select').val() ? $(this).find('select').val() : $(this).find('textarea').val();
                if($(this).hasClass('fy-radio-report')){
                    //单选
                    value = window.FormComponent.getRadioButtonValue(true)
                }else if($(this).hasClass('fy-checkbox-report')){
                    //多选
                    value = window.FormComponent.getCheckboxButtonValue(true);
                }else if($(this).hasClass('fy-multiselect-report')){
                    value = value+"|"+$($(this).find('select')[1]).val();
                }
                if(key && key != ''){
                    fromInfo[key] = value;
                }
            });
            gdt_tracker.push(["add_action", "TRACK_CONVERSION" , r['conversion_id_map'].form,
                {
                    "form_info":JSON.stringify(fromInfo)
                }
            ]);
        }
        gdt_tracker.push(["send"]);
    }
    /**
     * 函数节流方法
     */
    function throttle(method, delay){
        var timer = null;
        return function() {
            var context = this, args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                method.apply(context, args);
            }, delay);
        }
    }

    if(window.__reportParams && window.__reportParams.pv != 'no'){
        // 像素上报
        // var gdt_tracker = gdt_tracker || [];
        // gdt_tracker.push(["set_account_id", "4512569"]);
        // gdt_tracker.push(["add_action", "TRACK_CONVERSION", "18007"]);
        // gdt_tracker.push(["send"]);

        // var doc = document, h = doc.getElementsByTagName('head')[0], s = doc.createElement('script');
        // s.async = true;
        // s.src = "//qzs.qq.com/qzone/biz/res/gt.js";
        // h && h.insertBefore(s, h.firstChild);
        // 转化行为上报

        ActionDataReport.stayTime();
        ActionDataReport.sendPv();

        $('body').delegate('.data-report', 'click', function(e){
            var type = $(this).data('type');
            ActionDataReport.sendAction(type);

            if(type == 'map' || type == 'connectqq'){ // 地图跳转需要延迟一下
                var link = $(this).attr('href');
                window.setTimeout(function(){
                    window.location.href = link;
                }, 100);
                e.preventDefault();
            }

            if (type === 'phone') {
                pixelReport('phone')
            } 
        });

        $('.VAct_form').bind('data-report', function(event,param){
            ActionDataReport.sendAction('form');

            /*pixel report*/
            var formid = param
            pixelReport('form',formid)
        });
        $('body, #app').one('touchmove scroll', throttle(function(e){
            ActionDataReport.sendAction('slide');
            e.stopPropagation();
        }, 500));
    }
}());
